
package com.heimali.happyreader.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.heimali.happyreader.HappyReaderApplication;
import com.heimali.happyreader.R;
import com.heimali.happyreader.core.bean.Intro;
import com.heimali.happyreader.core.intf.ITaskListenerSimple;
import com.heimali.happyreader.core.manager.ArticleManager;
import com.heimali.happyreader.core.manager.GlobalManager;
import com.heimali.happyreader.ui.activity.DetailActivity;
import com.heimali.happyreader.ui.adapter.ArticleListAdapter;
import com.heimali.happyreader.ui.adapter.ArticleListAdapter.ViewHolder;
import com.heimali.happyreader.ui.fragment.helper.CommonListFragmentHelper;
import com.heimali.happyreader.ui.view.PullToRefreshListView;
import com.heimali.happyreader.ui.view.PullToRefreshListView.OnRefreshListener;
import com.heimali.happyreader.utils.AndroidUtils;
import com.heimali.happyreader.utils.NetCheckUtils;

import java.util.ArrayList;

public class CommonListFragment extends BaseListFragment implements IBaseFragment{

    public static String TAG = "CommonListFragment";

    private final int PAGE_SIZE = 10;

    private Context mContext;
    private ArticleListAdapter mAdapter;
    private PullToRefreshListView mListView;
    private View mLoadingView;
    private LinearLayout mLoadingLayout;
    private LinearLayout mNoMoreLayout;
    private LinearLayout mFirstLoadingLayout;
    
    private int mMinID = 0; // 当前显示的列表中的最小ID
    private int mMaxID = 0;
    private boolean mIsLoading = false;
    private boolean mIsNoMoreContent = false;
    
    private ArticleManager mArticleManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mArticleManager = GlobalManager.getInstance().articleManager;
        NetCheckUtils.registerDataTransReceiver(new NetChangeReceiver());
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_common_list, container, false);
        initView(v);
        if (HappyReaderApplication.commonUserInfo != null) {
            HappyReaderApplication.curUserInfo = HappyReaderApplication.commonUserInfo;
            showList();
        }
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onShow() {

    }

    @Override
    public void onHide() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        getActivity().finish();
        return true;
    }

    private void initView(View v) {
        mContext = getActivity();
        
        mFirstLoadingLayout = (LinearLayout) v.findViewById(R.id.first_loading_layout);
        
        mLoadingView = LayoutInflater.from(mContext).inflate(R.layout.loading_footer, null);
        mLoadingLayout = (LinearLayout) mLoadingView.findViewById(R.id.loading_layout);
        mNoMoreLayout = (LinearLayout) mLoadingView.findViewById(R.id.no_more_layout);
        
        mListView = (PullToRefreshListView) v.findViewById(R.id.article_list);
        mListView.addFooterView(mLoadingView, null, false);
        mAdapter = new ArticleListAdapter(mContext);
        mListView.setAdapter(mAdapter);
        mListView.setOnRefreshListener(new ListViewRefreshListener());
        mListView.setOnItemClickListener(new ListOnItemClickListener());
    }
    
    /**
     * 展现列表内容
     */
    private void showList() {
        mArticleManager.asyncLoadList(new LoadListListener(), mMinID, PAGE_SIZE);
        mIsLoading = true;
    }
    
    private void setShowLoading(boolean value) {
        mIsLoading = value;
        if (value) {
            mLoadingLayout.setVisibility(View.VISIBLE);
        }else {
            mLoadingLayout.setVisibility(View.GONE);
        }
    }

    class ListViewRefreshListener implements OnRefreshListener {
        @Override
        public void refresh() {
            if (!mIsLoading) {
                mIsLoading = true;
                mArticleManager.asyncLoadLastestList(new LoadListIncListener(), mMaxID);
            }
        }

        @Override
        public void loadNextPage() {
            if (!mIsLoading && !mIsNoMoreContent) {
                setShowLoading(true);
                mArticleManager.asyncLoadList(new LoadListListener(), mMinID, PAGE_SIZE);
            }
        }
    }

    class LoadListIncListener implements ITaskListenerSimple {
        @Override
        public Object taskFinished(Object param) {
            mIsLoading = false;
            mListView.refreshComplete();
            @SuppressWarnings("unchecked")
            ArrayList<Intro> list = (ArrayList<Intro>) param;
            if (list == null || list.isEmpty()) {
                Toast.makeText(mContext, R.string.pull_to_refresh_no_content, Toast.LENGTH_SHORT).show();
                return null;
            }

            int tmpMaxID = list.get(0).id;
            if (tmpMaxID > mMaxID) {
                mMaxID = tmpMaxID;
            }

            mAdapter.insertLastest(list);
            mAdapter.notifyDataSetChanged();
            Toast.makeText(mContext, getString(R.string.pull_to_refresh_last_time, list.size()), Toast.LENGTH_SHORT).show();
            return null;
        }

        @Override
        public Object taskFailed(Object param) {
            mIsLoading = false;
            mListView.refreshComplete();
            CommonListFragmentHelper.showFailedError(param);
            return null;
        }
    }

    class LoadListListener implements ITaskListenerSimple {
        @Override
        public Object taskFinished(Object param) {
            setShowLoading(false);
            if (mAdapter.getCount() == 0) {
                mFirstLoadingLayout.setVisibility(View.GONE);
                mListView.setVisibility(View.VISIBLE);
            }
            @SuppressWarnings("unchecked")
            ArrayList<Intro> list = (ArrayList<Intro>) param;
            if (list == null || list.isEmpty()) {
                return null;
            }
            
            if (list.isEmpty() || list.size() < PAGE_SIZE) {
                mIsNoMoreContent = true;
                mNoMoreLayout.setVisibility(View.VISIBLE);
            }

            int tmpMaxID = list.get(0).id;
            if (tmpMaxID > mMaxID) {
                mMaxID = tmpMaxID;
            }
            int tmpMinID = list.get(list.size() - 1).id;
            if (mMinID == 0 || tmpMinID < mMinID) {
                mMinID = tmpMinID;
            }
            mAdapter.insertOlder(list);
            mAdapter.notifyDataSetChanged();
            return null;
        }

        @Override
        public Object taskFailed(Object param) {
            CommonListFragmentHelper.showFailedError(param);
            setShowLoading(false);
            if (mFirstLoadingLayout.getVisibility() == View.VISIBLE) {
                mFirstLoadingLayout.setVisibility(View.GONE);
            }
            return null;
        }
    }

    class ListOnItemClickListener implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            ViewHolder holder = (ViewHolder) v.getTag();
            if (holder == null) {
                return;
            }

            int articleID = holder.id;
            Intent intent = new Intent(mContext, DetailActivity.class);
            intent.putExtra(DetailActivity.INTENT_DETAIL_ID_KEY, articleID);
            startActivity(intent);
        }
    }
    
    class NetChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isNetworkAvailable = NetCheckUtils.isNetworkAvailable();
            if (HappyReaderApplication.isNetworkAvailable == isNetworkAvailable) {
                return ;
            }
            HappyReaderApplication.isNetworkAvailable = isNetworkAvailable;
            
            if (isNetworkAvailable) {
                AndroidUtils.toast(R.string.network_available);
                if (mAdapter.getCount() == 0) {
                    mArticleManager.asyncLoadList(new LoadListListener(), mMinID, PAGE_SIZE);
                    mIsLoading = true;
                }
            }else {
                AndroidUtils.toast(R.string.network_not_available);
            }
        }
    }
}
